package com.example.vdmtest;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.example.vdmtest.MainTestAdapter.TestAdapterCallBack;
import com.example.vdmtest.MainTestAdapter.ViewHolder;
import com.example.vdmtest.tools.DownloadConfig;
import com.vivo.ic.dm.Config;
import com.vivo.ic.dm.DownloadInfo;
import com.vivo.ic.dm.DownloadManager;
import com.vivo.ic.dm.Downloads;
import com.vivo.ic.dm.impl.DownloadLifeListener;

import java.util.ArrayList;

public class MainActivity extends Activity implements TestAdapterCallBack, View.OnClickListener {
    private static final String TAG = MainApplication.PRE_TAG + "MainActivity";
    private Activity mContext;
    private EditText mEditView;
    private Button mSetBtn;
    private ListView mListView;
    private MainTestAdapter mAdapter;
    private ArrayList<MainTestItem> mItems = new ArrayList<MainTestItem>();
    private NetworkReceiver mNetWorkReceiver;
    private static final String[] PROJECTION = new String[]{
            Downloads.Column.STATUS,
            Downloads.Column.TOTAL_BYTES,
            Downloads.Column.CURRENT_BYTES,
            Downloads.Column.CONTROL,
            Downloads.Column.CURRENT_SPEED,

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_main);
        registerNetworkReceiver();
        ArrayList<String> urlArray = MainTestData.getUrlsFromFile();
        if (!urlArray.isEmpty()) {
            for (String url : MainTestData.getUrlsFromFile()) {
                mItems.add(new MainTestItem(url));
                Log.d(TAG, "getUrlsFromFile :" + url);
            }
        } else {
            for (String url : MainTestData.URLS) {
                mItems.add(new MainTestItem(url));
            }
        }

        mListView = (ListView) findViewById(R.id.list_view);
        mEditView = (EditText) findViewById(R.id.core_size_edit);
        mSetBtn = (Button) findViewById(R.id.set_core_size_btn);
        mSetBtn.setOnClickListener(this);
        if (!DownloadManager.getInstance().isAllDownloadComplete()) {
            mEditView.setEnabled(false);
            mSetBtn.setEnabled(false);
        } else {
            mEditView.setEnabled(true);
            mSetBtn.setEnabled(true);
        }
        mAdapter = new MainTestAdapter(mContext, mItems, this);
        mListView.setAdapter(mAdapter);

    }

    @Override
    protected void onResume() {
        super.onResume();
        update();
        // 注册下载回调
        DownloadManager.getInstance().addDownloadListener(mListener);
        sendBroadcast(new Intent("Downloads.Action.NOTI_HIDE"));
    }

    ;

    @Override
    protected void onPause() {
        super.onPause();
        // 解注册下载回调
        DownloadManager.getInstance().removeDownloadListener(mListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterNetworkReceiver();
        MainTestItem.AUTO_INT = 0;
    }

    /**
     * 创建下载进度回调，回调默认是在非主线程中，需要主动post出去进行处理
     */
    private DownloadLifeListener mListener = new DownloadLifeListener() {

        @Override
        public void onDownloadSizeChange(final DownloadInfo info, final long currentSize, final long totalSize) {
            // 下载大小发生改变
            MainTestItem item = getItem(info.mUri);
            if (item == null) {
                return;
            }
            item.percent = (int) (currentSize * 100 / totalSize);
            item.status = info.mStatus;
            item.control = info.mControl;
            Log.d(TAG, " onDownloadSizeChange(): " + " DownloadInfo:" + info
                    + " currentSize: " + currentSize + " totalSize: " + totalSize);
            updateItem(item);
        }

        @Override
        public void onDownloadSpeedChange(DownloadInfo info, long bytesPerSecond) {
            // 下载速度发生改变
            MainTestItem item = getItem(info.mUri);
            if (item == null) {
                return;
            }
            item.speed = bytesPerSecond;
            item.control = info.mControl;
            Log.d(TAG, " onDownloadSpeedChange(): " + " DownloadInfo:" + info + " bytesPerSecond: " + bytesPerSecond);
            updateItem(item);
        }

        @Override
        public void onDownloadStopped(DownloadInfo info, int finalStatus) {
            // 下载结束
            Log.d(TAG, "onDownloadStopped DownloadInfo: " + info);
            String tip = null;

            // 取消下载
            if (info.mStatus == Downloads.Impl.STATUS_CANCELED) {
                mContext.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(mContext, R.string.download_is_canceled, Toast.LENGTH_SHORT).show();
                    }
                });
                return;
            }

            // 存储空间不足
            if (info.mStatus == Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR) {
                mContext.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(mContext, R.string.download_space_not_enough, Toast.LENGTH_SHORT).show();
                    }
                });
                return;
            }

            // 下载失败
            if (!Downloads.Impl.isStatusSuccess(info.mStatus)
                    && !Downloads.Impl.isStatusInformational(info.mStatus)
                    && info.mControl != Downloads.Impl.CONTROL_PAUSED) {
                tip = getString(R.string.dm_noti_download_failed);
            }


            MainTestItem item = getItem(info.mUri);
            if (item == null) {
                return;
            }

            item.status = info.mStatus;
            item.speed = info.mSpeed;
            item.control = info.mControl;
            item.tip = tip;
            Log.d(TAG, " onDownloadStopped() item: " + item);
            updateItem(item);
            update();
        }

        @Override
        public void onDownloadPausedByNetChange(Long[] arg0) {
            update();
        }

        @Override
        public void onDownloadStartByNetChange(Long[] arg0) {
            update();
        }

        private void updateItem(final MainTestItem item) {

            mListView.post(new Runnable() {

                @Override
                public void run() {
                    final int position = mItems.indexOf(item);
                    final int firstPosition = mListView.getFirstVisiblePosition();
                    final int lastPosition = mListView.getLastVisiblePosition();

                    if (position <= lastPosition && position >= firstPosition) {
                        ViewHolder holder = null;
                        View view = mListView.getChildAt(position - firstPosition);
                        if (view != null && view.getTag() != null && view.getTag() instanceof ViewHolder) {
                            holder = (ViewHolder) view.getTag();
                            mAdapter.updateView(item, holder);
                        }
                    }
                }
            });
        }

    };

    MainTestItem getItem(String url) {
        for (MainTestItem item : mItems) {
            if (item.url.equals(url)) {
                return item;
            }
        }
        return null;
    }

    @Override
    public void onClick(View view) {
        String s = mEditView.getText().toString();
        if (!s.isEmpty()) {

            int i = Integer.valueOf(mEditView.getText().toString()).intValue();
            Config config = DownloadManager.getConfig();
            ((DownloadConfig) config).setMultiDownloadCoreSize(i);
            mEditView.setEnabled(false);
            mSetBtn.setEnabled(false);
        }


    }

    /**
     * 查询下载数据，并进行界面更新，此处使用了下载管理器中的DownloadQuene来进行排队，使数据库的增删改查有序进行不会错乱。
     */
    public void update() {
        Handler downloadHandler = DownloadManager.getInstance().getDownloadQuene();
        downloadHandler.post(updateThread);
    }

    Thread updateThread = new Thread(new Runnable() {

        @Override
        public void run() {
            ContentResolver cr = mContext.getContentResolver();
            for (MainTestItem item : mItems) {
                Cursor cursor = cr.query(Downloads.Impl.CONTENT_URI, PROJECTION,
                        Downloads.Column.URI + "=?", new String[]{item.url}, null);
                try {
                    if (cursor.moveToFirst()) {
                        item.status = cursor.getInt(0);
                        long totalBytes = cursor.getLong(1);
                        long currentBytes = cursor.getLong(2);
                        int percent = (int) (currentBytes * 100 / totalBytes);
                        item.percent = percent;
                        item.control = cursor.getInt(3);
                        item.speed = cursor.getInt(4);
                    } else {
                        item.clear();
                    }
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
            }
            mContext.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    mAdapter.notifyDataSetChanged();
                }
            });
        }
    });

    @Override
    public void onChange() {
        update();
    }

    private void registerNetworkReceiver() {
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        if (mNetWorkReceiver == null) {
            mNetWorkReceiver = new NetworkReceiver();
        }
        registerReceiver(mNetWorkReceiver, filter);
    }

    private void unRegisterNetworkReceiver() {
        if (mNetWorkReceiver != null) {
            unregisterReceiver(mNetWorkReceiver);
        }
    }

}
